package com.legal.service.practice.impl;

import com.legal.domain.dto.PracticeSubmissionDTO;
import com.legal.domain.entity.UserAnswer;
import com.legal.domain.po.PracticeDetail;
import com.legal.domain.po.PracticeRecord;
import com.legal.domain.po.Question;
import com.legal.domain.result.Result;
import com.legal.mapper.practice.PracticeDetailMapper;
import com.legal.mapper.practice.PracticeRecordMapper;
import com.legal.service.practice.IQuestionService;
import com.legal.service.practice.IUserPracticeStatsService;
import com.legal.service.practice.PracticeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaopeng
 * @version 1.0
 */
@Service
@RequiredArgsConstructor
public class PracticeServiceImpl implements PracticeService {

    private final PracticeRecordMapper practiceRecordMapper;

    private final PracticeDetailMapper practiceDetailMapper;

    private final IQuestionService questionService;

    private final IUserPracticeStatsService statsService;


    /**
     * 保存用户刷题记录
     * @param record
     * @param practiceDetails
     */
    @Override
    public void savePractice(PracticeRecord record, List<PracticeDetail> practiceDetails) {
        // 保存刷题记录
        practiceRecordMapper.insert(record);

        // 保存刷题详情
        for (PracticeDetail detail : practiceDetails) {
            practiceDetailMapper.insert(detail);
        }
    }

    /**
     * 提交用户刷题
     * @param submission
     */
    @Override
    public Result<Void>  submitPractice(PracticeSubmissionDTO submission) {
        // 1. 查询所有题目正确答案
        List<Question> questionList = questionService.getQuestionsByNos(submission.getQuestionNos());

        // 2. 比对答案并计算得分
        int correctCount = 0;
        List<PracticeDetail> practiceDetails = new ArrayList<>();

        for (UserAnswer userAnswer : submission.getAnswers()) {
            // 2.1 查找到当前题目,根据题目编号查找题目
            Question question = findQuestion(questionList, userAnswer.getQuestionNo());
            if (question == null) {
                return Result.error("题目不存在");
            }
            // 2.2 比对答案
            boolean isCorrect = question.getCorrectAnswer().equals(userAnswer.getAnswer());

            if (isCorrect) {
                correctCount++;
            }

            // 2.3 构建刷题详情
            practiceDetails.add(new PracticeDetail(
                    submission.getRecordNo(),
                    question.getQuestionNo(),
                    userAnswer.getAnswer(),
                    isCorrect ? 1 : 0
            ));
        }

        // 3. 计算得分 (满分100分)
        // 3.1 计算每题的平均分
        int totalQuestionCount = questionList.size();
        BigDecimal avgScore = BigDecimal.valueOf(100.0 / totalQuestionCount); // 每题的分数
        // 3.2 计算得分
        BigDecimal score = avgScore.multiply(BigDecimal.valueOf(correctCount));

        // 4. 创建刷题记录
        PracticeRecord record = new PracticeRecord()  // 使用构建器模式,利用 Lombok 的链式调用特性
                .setRecordNo(submission.getRecordNo())
                .setUserNo(submission.getUserNo())
                .setCategoryNo(submission.getCategoryNo())
                .setTotalQuestions(totalQuestionCount)
                .setCorrectCount(correctCount)
                .setScore(score)
                .setStartTime(submission.getStartTime())
                .setEndTime(LocalDateTime.now())  // 使用当前时间
                .setDuration((int) Duration.between(
                        submission.getStartTime(),
                        LocalDateTime.now()
                ).getSeconds());  // 计算持续时间(秒)

        // 5. 保存记录和详情
        savePractice(record, practiceDetails);

        // 7. 更新用户统计数据
        statsService.updateUserPracticeStats(submission.getUserNo(), submission.getCategoryNo(), record);

        return Result.ok();
    }

    /**
     * 根据题目编号查找题目
     *
     * @param questionList
     * @param questionNo
     * @return
     */
    private Question findQuestion(List<Question> questionList, String questionNo) {
        for (Question question : questionList) {
            if (question.getQuestionNo().equals(questionNo)) {
                return question;
            }
        }
        return null;
    }
}
